package cn.dapeng.t01;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.t01
 * @Description 打印字符串所有子串
 * @ClassName Substring
 * @Author xupenghong
 * @Date 2024/8/22 19:16
 * @Version 1.0.0
 */
public class Substring {

    /**
     * 使用递归方式实现
     *
     * @param str
     * @param index
     * @return
     */
    public static List<String> printSubstring(String str, int index) {

        if (Objects.isNull(str) || index > str.length()) {
            return null;
        }

        List<String> list = new ArrayList<>();
        char[] chars = str.toCharArray();
        int length = chars.length;
        for (int i = length - 1; i >= index; i--) {
            list.add(new String(chars, index, i - index + 1));
        }

        List<String> l = printSubstring(str, index + 1);
        if (l != null) {
            list.addAll(l);
        }
        return list;
    }

    /**
     * 非递归版本
     *
     * @param str
     * @return
     */
    public static List<String> printSubstring(String str) {
        if (str == null || str.isBlank()) {
            return null;
        }
        List<String> list = new ArrayList<>();
        char[] chars = str.toCharArray();

        int length = chars.length;
        for (int i = 0; i < length; i++) {
            list.addAll(printSubstring(chars, i, length));
        }
        return list;
    }

    private static List<String> printSubstring(char[] chars, int start, int end) {
        List<String> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (int i = start; i < end; i++) {
            sb.append(chars[i]);
            list.add(sb.toString());
        }

        return list;
    }

    public static void main(String[] args) {
        String str = "中国必胜";

        System.out.println(printSubstring(str));

        System.out.println(printSubstring(str, 0));
    }
}
